package com.bw.module_main

import android.graphics.Rect
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.Interpolator
import android.widget.ImageView
import androidx.viewpager2.widget.ViewPager2
import kotlin.math.max
import kotlin.math.min

class GuideIndicator(private val indicatorView: ImageView) {
    
    private val interpolator: Interpolator = AccelerateDecelerateInterpolator()
    private var viewPager: ViewPager2? = null
    private var itemCount = 0
    
    fun setViewPager(viewPager: ViewPager2) {
        this.viewPager = viewPager
        
        // 获取ViewPager的适配器项数量
        itemCount = viewPager.adapter?.itemCount ?: 0
        
        // 设置ViewPager的页面变化监听器
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)
                
                // 计算进度
                val progress = position + positionOffset
                updateIndicator(progress)
            }
        })
        
        // 初始更新指示器
        updateIndicator(0f)
    }
    
    private fun updateIndicator(progress: Float) {
        if (itemCount <= 1) return
        
        // 计算指示器的clip范围
        val maxClip = (indicatorView.width * (itemCount - 1).toFloat() / itemCount).toInt()
        val clipPosition = (maxClip * progress / (itemCount - 1)).toInt()
        
        // 确保clipPosition在有效范围内
        val clippedPosition = max(0, min(maxClip, clipPosition))
        
        // 更新指示器的显示
        indicatorView.post {
            indicatorView.setClipBounds(Rect(clippedPosition, 0, clippedPosition + indicatorView.width / itemCount, indicatorView.height))
        }
    }
    
    // 使用Android框架的Rect类
}